<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket 测试页面</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .status { margin: 10px 0; padding: 10px; border-radius: 4px; }
        .connected { background: #d4edda; color: #155724; }
        .disconnected { background: #f8d7da; color: #721c24; }
        #messages { height: 300px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; margin-top: 10px; }
        .message { margin: 5px 0; }
    </style>
</head>
<body>
<h1>WebSocket 单用户登录测试</h1>

<div class="status" id="status">未连接</div>

<div>
    <input type="text" id="username" placeholder="输入用户名" style="width: 200px;">
    <button onclick="connectWebSocket()">连接</button>
    <button onclick="disconnectWebSocket()" disabled>断开连接</button>
</div>

<div style="margin-top: 20px;">
    <input type="text" id="messageInput" placeholder="输入消息内容" style="width: 300px;" disabled>
    <button onclick="sendMessage()" disabled>发送消息</button>
</div>

<div id="messages"></div>

<script>
    let socket = null;
    let username = null;
    let connected = false;

    function updateStatus() {
        const statusDiv = document.getElementById('status');
        if (connected) {
            statusDiv.className = 'status connected';
            statusDiv.textContent = `已连接（用户：${username}）`;
        } else {
            statusDiv.className = 'status disconnected';
            statusDiv.textContent = '未连接';
        }
    }

    function addMessage(content, isSystem = false) {
        const messages = document.getElementById('messages');
        const msgDiv = document.createElement('div');
        msgDiv.className = 'message';
        msgDiv.style.color = isSystem ? 'blue' : 'black';
        msgDiv.textContent = content;
        messages.appendChild(msgDiv);
        messages.scrollTop = messages.scrollHeight;
    }

    function connectWebSocket() {
        const input = document.getElementById('username');
        username = input.value.trim();

        if (!username) {
            alert('请输入用户名');
            return;
        }

        // 创建带用户ID参数的WebSocket连接
        socket = new WebSocket(`ws://localhost:9900/arbot/ws?userId=${encodeURIComponent(username)}`);

        socket.onopen = () => {
            connected = true;
            updateStatus();
            addMessage('WebSocket 连接已建立', true);

            // 启用消息输入框和按钮
            document.getElementById('messageInput').disabled = false;
            document.querySelector('button[onclick="sendMessage()"]').disabled = false;
            document.querySelector('button[onclick="disconnectWebSocket()"]').disabled = false;
        };

        socket.onmessage = (event) => {
            const message = event.data;

            // 处理强制下线通知
            if (message === "KICKED_OUT") {
                addMessage('您已被强制下线', true);
                disconnectWebSocket();
                return;
            }

            addMessage(`收到消息: ${message}`);
        };

        socket.onclose = (event) => {
            connected = false;
            updateStatus();
            addMessage(`连接已关闭: ${event.reason || '正常关闭'}`, true);

            // 禁用消息输入框和按钮
            document.getElementById('messageInput').disabled = true;
            document.querySelector('button[onclick="sendMessage()"]').disabled = true;
            document.querySelector('button[onclick="disconnectWebSocket()"]').disabled = true;
        };

        socket.onerror = (error) => {
            addMessage(`发生错误: ${error.message}`, true);
            console.error('WebSocket Error:', error);
        };
    }

    function disconnectWebSocket() {
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.close();
        }
        username = null;
    }

    function sendMessage() {
        const input = document.getElementById('messageInput');
        const message = input.value.trim();

        if (!message || !socket || socket.readyState !== WebSocket.OPEN) {
            return;
        }

        try {
            socket.send(message);
            addMessage(`发送消息: ${message}`);
            input.value = '';
        } catch (error) {
            addMessage(`发送失败: ${error.message}`, true);
        }
    }

    // 页面卸载时关闭连接
    window.addEventListener('beforeunload', () => {
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.close();
        }
    });
</script>
</body>
</html>
